import os
from pathlib import Path
from typing import Optional

from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    PROJECT_NAME: str = "AI Web"  #项目名称
    VERSION: str = "0.1.0"  #项目版本
    API_V1_STR: str = "/api"  # api版本前缀

    #项目所在目录,用于获取其它文件路径
    PROJECT_PATH: str = ''

    # Chat Provider settings
    CHAT_PROVIDER: str = os.getenv("CHAT_PROVIDER", "openai")

    # Embeddings settings
    EMBEDDINGS_PROVIDER: str = os.getenv("EMBEDDINGS_PROVIDER", "openai")

    # OpenAI settings
    OPENAI_API_BASE: str = os.getenv("OPENAI_API_BASE", "https://api.openai.com/v1")
    OPENAI_API_KEY: str = os.getenv("OPENAI_API_KEY", "your-openai-api-key-here")
    OPENAI_MODEL: str = os.getenv("OPENAI_MODEL", "gpt-4")
    OPENAI_EMBEDDINGS_MODEL: str = os.getenv("OPENAI_EMBEDDINGS_MODEL", "text-embedding-ada-002")
    OPENAI_EMBEDDINGS_DIMENSIONS: int = int(os.getenv("OPENAI_EMBEDDINGS_DIMENSIONS", 0))

    #langfuse
    LANGFUSE_PUBLIC_KEY:str = os.getenv("LANGFUSE_PUBLIC_KEY", "pk-xxx")
    LANGFUSE_SECRET_KEY:str = os.getenv("LANGFUSE_SECRET_KEY", "sk-xxx")
    LANGFUSE_URL:str = os.getenv("LANGFUSE_URL", "https://us.cloud.langfuse.com")

    # MySQL settings
    MYSQL_SERVER: str = os.getenv("MYSQL_SERVER", "localhost")
    MYSQL_PORT: int = int(os.getenv("MYSQL_PORT", "3306"))
    MYSQL_USER: str = os.getenv("MYSQL_USER", "aip")
    MYSQL_PASSWORD: str = os.getenv("MYSQL_PASSWORD", "aip")
    MYSQL_DATABASE: str = os.getenv("MYSQL_DATABASE", "aip")
    SQLALCHEMY_DATABASE_URI: Optional[str] = None

    # 文件下载保存路径
    FILE_DOWNLOAD_PATH: str = os.getenv("FILE_DOWNLOAD_PATH", "uploads")

    # milvus向量数据库配置
    MILVUS_API_URL: str = os.getenv("MILVUS_API_URL", "http://localhost:19530")
    MILVUS_API_TOKEN: str = os.getenv("MILVUS_API_TOKEN", "root:Milvus")

    SECRET_KEY: str = os.getenv("SECRET_KEY", "your-secret-key-here")
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "10080"))

    @property
    def get_database_url(self) -> str:
        if self.SQLALCHEMY_DATABASE_URI:
            return self.SQLALCHEMY_DATABASE_URI

        self.SQLALCHEMY_DATABASE_URI = (
            f"mysql+mysqlconnector://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}"
            f"@{self.MYSQL_SERVER}:{self.MYSQL_PORT}/{self.MYSQL_DATABASE}"
        )
        # print(self.SQLALCHEMY_DATABASE_URI)
        return self.SQLALCHEMY_DATABASE_URI

    #日志配置文件名
    LOGGING_CONF_NAME: str = os.getenv("LOGGING_CONF_NAME", "logging.conf")

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.PROJECT_PATH = Path(__file__).resolve().parents[2]

    def get_logging_conf_name_path(self) -> str:
        return f'{self.PROJECT_PATH}{os.sep}{self.LOGGING_CONF_NAME}'

    def get_alembic_int_path(self) -> str:
        return f'{self.PROJECT_PATH}{os.sep}alembic.ini'


settings = Settings()
